package cn.edu.csust.coursecard.common;

public class Guarded<T>{
    
    private T response;
    
    //获取结果
    public T getResult(){
        synchronized (this){
            while(response == null){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return  response;
        }
    }
    
    //指定超时时间
    public T getResult(long timeout){
        synchronized (this){
            //记录等待的开始时间
            long begin = System.currentTimeMillis();
            //记录经历的时间
            long passTime = 0;
            while(response == null){
                if(passTime >= timeout){
                    break;
                }
                try {
                    this.wait(timeout - passTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passTime = System.currentTimeMillis() - begin;
            }
            return  response;
        }
    }
    
    public void setResult(T data){
        synchronized (this){
            response = data;
            //唤醒等待结果线程
            this.notifyAll();
        }
    }
    
}